`
https://leetcode.cn/problems/maximum-value-at-a-given-index-in-a-bounded-array/
`

/**
 * @param {number} n
 * @param {number} index
 * @param {number} maxSum
 * @return {number}
 */
var maxValue = function (n, index, maxSum) {
  if (maxSum - n <= 0) return 1

  // 一个最大值为 k ，长度为 len 的数组的总和
  const calc = (k, len) => {
    if (len > k) {
      return Math.floor(k * (k + 1) / 2) + len - k
    } else {
      return (k + k - len + 1) * len / 2
    }
  }

  // nums[index] 能否是 k
  const check = (k) => {
    return k + calc(k - 1, index) + calc(k - 1, n - index - 1) <= maxSum
  }

  let left = 0, right = maxSum + 1
  while (left + 1 < right) {
    const mid = left + Math.floor((right - left) / 2)
    if (check(mid)) {
      left = mid
    } else {
      right = mid
    }
  }
  return left
};